package com.shuangyu.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.shuangyu.common.BaseContext;
import com.shuangyu.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录
 */
@WebFilter(filterName = "logincheckfilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;



        //1.获取url请求
        String requestURI = request.getRequestURI();

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/logout"
        };

        //2.判断url是否放行
        Boolean check = check(urls, requestURI);

        //3.不拦截的放行
        if (check){
            filterChain.doFilter(request, response);
            return;
        }

        //4.判断是否已登录，如果已登录就放行
        if (request.getSession().getAttribute("employee") != null){
            BaseContext.setCurrentId((long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }

        //4-1.判断用户是否已登录
        if (request.getSession().getAttribute("phone") != null){
            BaseContext.setCurrentId((long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }

        //5.不放行
        log.info("拦截器捕获到：{}", request.getRequestURI());
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public Boolean check(String[] urls, String requestUrl){
        for (String url: urls) {
            boolean b = PATH_MATCHER.match(url, requestUrl);
            if (b){
                return true;
            }
        }
        return false;
    }
}
